package rpg.data;

import java.io.File;
import java.util.List;

import org.jdom.Element;

import rpg.ai.NpcAI;
import rpg.map.Creature;
import rpg.map.Effect;
import rpg.map.Item;
import rpg.map.Location;
import rpg.map.Map;
import square.data.DataGroup;

/**
 * 
 * @author Pedro Silva Moreira
 */
public class MapXML implements LoaderXML {
	private static MapXML singleton = new MapXML();
	
	// Creation
	private MapXML() {
	}
	
	// Instance
	public static MapXML instance() {
		return singleton;
	}
	
	// Load
	@SuppressWarnings("unchecked")
	public void load(String group, String name, Element origin) {
		Element elem = XML.loadXML(XML.DATA_FOLDER + "maps" + File.separator
				+ group + File.separator + name + ".xml");
		
		Map map = new Map(elem.getAttributeValue("name"), Integer.valueOf(elem
				.getAttributeValue("x")), Integer.valueOf(elem
				.getAttributeValue("y")), Integer.valueOf(elem
				.getAttributeValue("z")));
		elem.getAttribute("x");
		
		// Group
		map.setGroup(group);
		
		// Name
		map.setName(name);
		
		// Attributes
		List<Element> squares = elem.getChildren("square");
		for (int i = 0; i < squares.size(); i++) {
			Element square = squares.get(i);
			int x = Integer.valueOf(square.getAttributeValue("x"));
			int y = Integer.valueOf(square.getAttributeValue("y"));
			int z = Integer.valueOf(square.getAttributeValue("z"));

			Location location = (Location) map.getLocation(x, y, z);

			// Items
			List<Element> items = square.getChildren("item");
			for (int j = 0; j < items.size(); j++) {
				Element itemElem = items.get(j);

				Item item = new Item(itemElem.getAttributeValue("name"));
				location.addItem(item);
			}

			// Creature
			Element creatureElem = square.getChild("creature");
			if (creatureElem != null) {
				Creature creature = new Creature(
						creatureElem.getAttributeValue("name"));
				CreatureXML.parseData(creatureElem, creature.getData());

				NpcAI ai = new NpcAI(creature);
				ai.startThink();

				location.setCreature(creature);
			}

			// Effects
			List<Element> effects = square.getChildren("effect");
			for (int j = 0; j < effects.size(); j++) {
				Element effectElem = effects.get(j);

				Effect effect = new Effect(
						effectElem.getAttributeValue("name"),
						Integer.valueOf(effectElem.getAttributeValue("time")));
				location.addEffect(effect);
			}
		}

		DataGroup.getMaps().add(map);
	}
}
